package com.amigo.online.provider.video.interceptor;

import java.lang.reflect.Method;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.amigo.online.common.base.security.LocalUser;
import com.amigo.online.common.core.response.StatusCode;
import com.amigo.online.common.core.security.IgnoreSecurity;
import com.amigo.online.common.util.StringUtils;
import com.amigo.online.provider.video.exception.TokenException;
import com.amigo.online.provider.video.service.TokenManagerService;

/**
 * token拦截器
 *
 * @author amigo
 */
@Component
public class TokenInterceptor implements HandlerInterceptor {
    private static final Logger logger = LoggerFactory.getLogger(TokenInterceptor.class);

    @Resource
    private TokenManagerService tokenManagerService;

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
            throws Exception {
        LocalUser.removeUser();
        //super.afterCompletion(request, response, handler, ex);

        //logger.info("----------执行 1 afterCompletion -----------");
        logger.info("请求结束!请求线程名:" + Thread.currentThread().getName() + ",请求路径:" + request.getRequestURI());
    }

    public void afterConcurrentHandlingStarted(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {
        //super.afterConcurrentHandlingStarted(request, response, handler);

        //logger.info("----------执行 1 afterConcurrentHandlingStarted -----------");
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
                           ModelAndView modelAndView) throws Exception {
        //super.postHandle(request, response, handler, modelAndView);

        //logger.info("----------执行 1 postHandle -----------");
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }
        HandlerMethod handlerMethod = (HandlerMethod) handler;
        Method method = handlerMethod.getMethod();
        //logger.info("Method:" + method.getName() + ", IgnoreSecurity: "+ method.isAnnotationPresent(IgnoreSecurity.class));
        logger.info("请求开始!请求线程名:" + Thread.currentThread().getName() + ",请求路径" + request.getRequestURI());
        String token = request.getHeader("ACCESS_TOKEN");
        if (StringUtils.isEmpty(token)) {
            token = request.getParameter("access_token");
        }
        if (method.isAnnotationPresent(IgnoreSecurity.class)) {
            if (StringUtils.isNotEmpty(token)) {
                tokenManagerService.checkToken(token);
            }
            return true;
        }
        if (StringUtils.isEmpty(token)) {
            throw new TokenException(StatusCode.UNAUTHORIZED);
        }
        // 检查 token 有效性
        if (!tokenManagerService.checkToken(token)) {
            throw new TokenException(StatusCode.UNAUTHORIZED);
        }
        return true;
    }
}
